<?php

namespace App\Domain\Menu\Services;

use App\Domain\Menu\Dao\MenuDao;
use App\Domain\Menu\Models\MenuModel;
use App\Exceptions\BadRequestException;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;

class MenuService
{
    public function create($param)
    {
        $menuDao = new MenuDao();
        $data = $menuDao->findByName($param['name']);
        if ($data['name'] === $param['name']) {
            throw new BadRequestException('菜单已存在');
        }
        $res = $menuDao->create([
            'name' => $param['name'],
            'url' => $param['url'],
            'pid' => $param['pid'],
            'sort' => $param['sort'],
        ]);
        return $res;
    }

    /**
     * 菜单列表
     * @param $params
     * @return LengthAwarePaginator|Builder[]|Collection
     */
    public function list($params)
    {
        $query = MenuModel::query()
            ->select('menu.*')
            ->where('menu.state', 1);
        $query = $query->where(function (Builder $query) use ($params) {
            if (isset($params['name']))
                $query->where('name', 'like', "%{$params['name']}%");
            if (isset($params['url']))
                $query->where('url', 'like', "%{$params['url']}%");
        });
        if (isset($params['pageSize']) && isset($params['currentPage'])) {
            return $query->paginate($params['pageSize'], ['*'], 'page', $params['currentPage']);
        } else {
            return $query->get();
        }
    }

    //删除菜单
    public function del($id)
    {
        $menuDao = new MenuDao();
        $data = $menuDao->del($id);
        return $data;
    }

    //菜单更改
    public function update($param)
    {
        $menuDao = new MenuDao();
        $data = $menuDao->findById($param['id']);
        if (empty($data)) {
            throw new BadRequestException('菜单不存在');
        }
        $res = $menuDao->update($data, $param);
        return $res;
    }
}
